"use client";

import {
  Avatar,
  Box,
  HStack,
  Text,
  VStack,
  useColorModeValue,
} from "@chakra-ui/react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
import type { ChatMessage } from "@/lib/types";

interface Props {
  message: ChatMessage;
}

export function Message({ message }: Props) {
  const isUser = message.role === "user";
  const bubbleBg = isUser ? "accent.500" : "bg.glass";
  const align = isUser ? "flex-end" : "flex-start";
  const radius = isUser
    ? "22px 22px 6px 22px"
    : "22px 22px 22px 6px";

  return (
    <VStack align={align} spacing={2} w="100%">
      <HStack
        align="flex-start"
        spacing={3}
        maxW="min(760px, 90%)"
        flexDir={isUser ? "row-reverse" : "row"}
      >
        <Avatar
          size="sm"
          name={isUser ? "You" : "Eugene"}
          bg={isUser ? "accent.600" : "lumen.500"}
          color="white"
          getInitials={(n) => n[0]}
        />
        <Box
          bg={bubbleBg}
          backdropFilter="saturate(140%) blur(14px)"
          border="1px solid"
          borderColor={isUser ? "accent.400" : "border.subtle"}
          px={4}
          py={3}
          borderRadius={radius}
          boxShadow={isUser ? "0 8px 24px -12px rgba(58,79,247,0.55)" : "none"}
          color={isUser ? "white" : "text.primary"}
          lineHeight={1.55}
          fontSize="15px"
          sx={{
            "p:not(:last-of-type)": { mb: 2 },
            "ol, ul": { pl: 5, mb: 2 },
            code: {
              bg: useColorModeValue("blackAlpha.100", "whiteAlpha.200"),
              px: "4px",
              borderRadius: "4px",
              fontSize: "13px",
            },
            pre: {
              bg: "surface.200",
              border: "1px solid",
              borderColor: "border.subtle",
              p: 3,
              borderRadius: "lg",
              overflowX: "auto",
              fontSize: "13px",
              my: 2,
            },
            a: { color: "accent.200", textDecoration: "underline" },
            table: { borderCollapse: "collapse", width: "100%", mb: 2 },
            "th, td": {
              border: "1px solid",
              borderColor: "border.subtle",
              px: 2,
              py: 1,
              textAlign: "left",
            },
          }}
        >
          {message.content ? (
            <ReactMarkdown remarkPlugins={[remarkGfm]}>
              {message.content}
            </ReactMarkdown>
          ) : (
            <Text opacity={0.6} fontStyle="italic">
              thinking…
            </Text>
          )}
        </Box>
      </HStack>
      {/* Tool-call trace intentionally hidden in chat. Inspect tool calls
          in the right-pane "Tool Calls" tab. */}
    </VStack>
  );
}
